/**
 * Created by Administrator on 2015/8/6.
 */
var markdown = require('markdown').markdown;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

function Post(name, head, title, tags, post) {
    this.name = name;
    this.head = head;
    this.title = title;
    this.tags = tags;
    this.post = post;
}

module.exports = Post;

var postSchema = new mongoose.Schema({
    name: String,
    head: String,
    time: {
        data: Date,
        year: String,
        month: String,
        day: String,
        minute: String
    },
    title: String,
    tags: [String],
    post: String,
    comments: [String],
    reprint_info: {
        reprint_from:{
            name: String,
            day: String,
            title: String
        },
        reprint_to: [{
            name: String,
            day: String,
            title: String
        }]
    },
    pv: Number
},{
    collection: 'posts'
});

var postModel = mongoose.model('Post', postSchema);

Post.prototype.save = function (callback) {
    var date = new Date();
    var time = {
        date: date,
        year: date.getFullYear(),
        month: date.getFullYear() + "-" + (date.getMonth() + 1),
        day: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
        minute: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ' '
        + date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
    }
    //要存入数据库的文档
    var post = {
        name: this.name,
        head: this.head,
        time: time,
        title: this.title,
        tags: this.tags,
        post: this.post,
        comments: [],
        reprint_info: {},
        pv: 0
    };
    
    var postDoc = new postModel(post);
    postDoc.save(function (err, post) {
        callback(err, post);
    })
}

//name指的是用户名的name
Post.getTen = function(name,pageNo,pageSize,callback) {
    var condition = name ? {name: name} : {};
    console.log("-----------进入分页----------,name:" + name + ",pageNo:" + pageNo + ",pageSize:" + pageSize);
    postModel.find(condition).limit(pageSize).skip((pageNo-1)*pageSize).exec(function (err,docs) {
        docs.forEach(function (doc) {
            doc.post = markdown.toHTML(doc.post);
        });
        postModel.count({name: name}).exec(function (err,total) {
           callback(err, docs, total);
        })
    });
};

Post.getOne = function (_id, callback) {
    postModel.findOne({_id: _id
    }, function (err, doc) {
        if(doc) {
            postModel.update({_id: _id},{"$inc": {"pv":1}}, function (err) {
                doc.post = markdown.toHTML(doc.post);
                doc.comments.forEach(function (comment) {
                    comment.content = markdown.toHTML(comment.content);
                });
                callback(err, doc);
            })
        }
    });
};

Post.getOneOld = function (name, day, title, callback) {
    postModel.findOne({
        name: name,
        "time.day": day,
        title: title
    }, function (err, doc) {
        if(doc) {
            postModel.update({
                name: name,
                "time.day": day,
                title: title
            },{
                "$inc": {"pv":1}
            }, function (err) {
                doc.post = markdown.toHTML(doc.post);
                doc.comments.forEach(function (comment) {
                    comment.content = markdown.toHTML(comment.content);
                });
                callback(err, doc);
            })
        }
    });
};

//查询文章详情(markdown格式,不用转换)
Post.edit = function (_id, name, callback) {
    postModel.findOne({_id: _id, name:name}, function (err, doc) {
        callback(err, doc);
    });
};


//更新一篇文章及其相关信息
Post.update = function (name, _id, post, callback) {
    postModel.update({name:name, _id: _id}, {$set: {post: post}}, function (err) {
        callback(err);
    })
};

//返回所有文章的存档信息
Post.getArchive = function(callback) {
    postModel.find({},"name time title").sort({time: -1}).exec(function (err, docs) {
        callback(err, docs);
    });
};

//返回所有标签
Post.getTags = function(callback) {
    postModel.distinct("tags", function (err, docs) {
        callback(err, docs);
    });
};

//返回含有特定标签的所有文章
Post.getTag = function(tag, callback) {
    postModel.find({tags:tag}).select("name time title").sort({time: -1}).exec(function (err, docs) {
        callback(err, docs);
    });
};

//返回通过标题关键字查询的所有文章信息
Post.search = function (keyword, callback) {
    var pattern = new RegExp(keyword, "i");
    postModel.find({title: pattern}).select("name time title").sort({time: -1}).exec(function (err, docs) {
        callback(err, docs);
    });
};

//转载一篇文章
Post.reprint = function(reprint_from,reprint_to,callback) {
    //找到被转载的文章的原文档
    postModel.findOne({"name":reprint_from.name, "time.day":reprint_from.day, "title":reprint_from.title})
        .exec(function (err, doc) {
        if(err) {
            console.log("-----------------error1");
            return callback(err);
        }
        var date = new Date();
        var time = {
            date: date,
            year : date.getFullYear(),
            month : date.getFullYear() + "-" + (date.getMonth() + 1),
            day : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
            minute : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
        }


        //换一些信息，保留一些信息
        //reprint_from 原文章的信息
        //reprint_to   自己想要转载
        doc.name = reprint_to.name;
        doc.head = reprint_to.head;
        doc.time = time;
        doc.title = (doc.title.search(/[转载]/) > -1) ? doc.title : "[转载]" + doc.title;
        doc.comments = [];
        doc.reprint_info = {"reprint_from": reprint_from};
        doc.pv = 0;
        //更新被转载的原文档的 reprint_info 内的 reprint_to
        postModel.update({
            "name": reprint_from.name,
            "time.day": reprint_from.day,
            "title": reprint_from.title
        }, {
            $push: {
                "reprint_info.reprint_to": {
                    "name": doc.name,
                    "day": time.day,
                    "title": doc.title
                }
            }
        }, function (err) {
            if(err) {
                console.log("-----------------error2");
                return callback(err);
            }
        });
        //将转载生成的副本修改后存入数据库，并返回存储后的文档
        var newDoc = doc.toObject();//或者使用 var newJson = doc.toJSON();
        delete newDoc._id; //注意要删掉原来的 _id
        var postDoc = new postModel(newDoc);
        postDoc.save(function (err, post) {
            if(err) {
                console.log("-----------------error3; "+err);
            }
            callback(err, post);
        });
    });

};

//假如我们要删除一篇转载来的文章时，
// 还要将被转载的原文章所在文档的 reprint_to 删除遗留的转载信息。
Post.remove = function(name, day, title, callback) {
    postModel.findOne({
        "name": name,
        "time.day": day,
        "title": title
    }, function (err, doc) {
        if (err) {
            return callback(err);
        }
        //如果有 reprint_from，即该文章是转载来的，先保存下来 reprint_from
        var reprint_from = "";
        if (doc.reprint_info.reprint_from) {
            reprint_from = doc.reprint_info.reprint_from;
        }
        if (reprint_from != "") {
            //更新原文章所在文档的 reprint_to
            postModel.update({
                "name": reprint_from.name,
                "time.day": reprint_from.day,
                "title": reprint_from.title
            }, {
                $pull: {
                    "reprint_info.reprint_to": {
                        "name": name,
                        "day": day,
                        "title": title
                    }
                }
            }, function (err) {
                if (err) {
                    return callback(err);
                }
            });
        }
    });
    postModel.remove({
        "name": name,
        "time.day": day,
        "title": title
    }, function (err) {
        callback(err);
    });

};